import axios from 'axios';
import useLogin from '@/stores/login';
import router from '@/router';
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL, // 设置基础 URL，根据实际情况修改 '/接口前缀', //import.meta.env.VITE_BASE_URL
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
  timeout: 5000, // 设置请求超时时间
});

service.interceptors.request.use(
  (config) => {
    const useStore = useLogin();
    const token = useStore.token;
    if (token) {
      config.headers.Authorization = `${token}`;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response && response.data.code === 50) {
      const loginStore = useLogin();
      // 清除本地存储中的 token
      loginStore.clearToken();
      router.push('/login');
      // eslint-disable-next-line no-undef
      ElMessage({
        message: '请重新登录',
        type: 'error',
      });
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);
export default service;
